package com.ruoyi.system.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.PetCategoryMapper;
import com.ruoyi.system.domain.PetCategory;
import com.ruoyi.system.service.IPetCategoryService;

/**
 * 宠物分类Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-30
 */
@Service
public class PetCategoryServiceImpl implements IPetCategoryService 
{
    @Autowired
    private PetCategoryMapper petCategoryMapper;

    /**
     * 查询宠物分类
     * 
     * @param categoryId 宠物分类主键
     * @return 宠物分类
     */
    @Override
    public PetCategory selectPetCategoryByCategoryId(Long categoryId)
    {
        return petCategoryMapper.selectPetCategoryByCategoryId(categoryId);
    }

    /**
     * 查询宠物分类列表
     * 
     * @param petCategory 宠物分类
     * @return 宠物分类
     */
    @Override
    public List<PetCategory> selectPetCategoryList(PetCategory petCategory)
    {
        // 直接查询所有分类，然后在内存中进行过滤
        List<PetCategory> allCategories = petCategoryMapper.selectPetCategoryList(new PetCategory());
        
        // 如果没有按分类名称搜索，直接返回所有分类
        if (petCategory.getCategoryName() == null || petCategory.getCategoryName().isEmpty()) {
            return allCategories;
        }
        
        // 收集匹配的分类及其父级分类
        Set<Long> matchedCategoryIds = new HashSet<>();
        Set<Long> parentIds = new HashSet<>();
        
        // 查找匹配的分类
        for (PetCategory category : allCategories) {
            if (category.getCategoryName() != null && 
                category.getCategoryName().contains(petCategory.getCategoryName())) {
                matchedCategoryIds.add(category.getCategoryId());
                // 如果是二级分类，还需要添加其父级分类
                if (category.getParentId() != null && category.getParentId() != 0) {
                    parentIds.add(category.getParentId());
                }
            }
        }
        
        // 合并需要显示的分类ID
        Set<Long> categoryIdsToShow = new HashSet<>(matchedCategoryIds);
        categoryIdsToShow.addAll(parentIds);
        
        // 过滤出需要显示的分类
        return allCategories.stream()
            .filter(category -> categoryIdsToShow.contains(category.getCategoryId()))
            .collect(Collectors.toList());
    }

    /**
     * 查询所有有效的宠物分类
     * 
     * @return 宠物分类集合
     */
    @Override
    public List<PetCategory> selectActivePetCategories()
    {
        return petCategoryMapper.selectActivePetCategories();
    }

    /**
     * 新增宠物分类
     * 
     * @param petCategory 宠物分类
     * @return 结果
     */
    @Override
    public int insertPetCategory(PetCategory petCategory)
    {
        // 设置创建时间
        petCategory.setCreateTime(DateUtils.getNowDate());
        
        // 处理树形结构信息
        if (petCategory.getParentId() == null) {
            petCategory.setParentId(0L);
        }
        
        if (petCategory.getParentId().equals(0L)) {
            // 顶级分类
            petCategory.setLevel(1);
            petCategory.setAncestors("0");
        } else {
            // 子分类
            PetCategory parentCategory = petCategoryMapper.selectPetCategoryByCategoryId(petCategory.getParentId());
            if (parentCategory != null) {
                petCategory.setLevel(parentCategory.getLevel() + 1);
                petCategory.setAncestors(parentCategory.getAncestors() + "," + petCategory.getParentId());
            } else {
                petCategory.setLevel(1);
                petCategory.setAncestors("0");
            }
        }
        
        return petCategoryMapper.insertPetCategory(petCategory);
    }

    /**
     * 修改宠物分类
     * 
     * @param petCategory 宠物分类
     * @return 结果
     */
    @Override
    public int updatePetCategory(PetCategory petCategory)
    {
        petCategory.setUpdateTime(DateUtils.getNowDate());
        return petCategoryMapper.updatePetCategory(petCategory);
    }

    /**
     * 批量删除宠物分类
     * 
     * @param categoryIds 需要删除的宠物分类主键
     * @return 结果
     */
    @Override
    public int deletePetCategoryByCategoryIds(Long[] categoryIds)
    {
        return petCategoryMapper.deletePetCategoryByCategoryIds(categoryIds);
    }

    /**
     * 删除宠物分类信息
     * 
     * @param categoryId 宠物分类主键
     * @return 结果
     */
    @Override
    public int deletePetCategoryByCategoryId(Long categoryId)
    {
        return petCategoryMapper.deletePetCategoryByCategoryId(categoryId);
    }

    /**
     * 校验分类编码是否唯一
     * 
     * @param petCategory 宠物分类信息
     * @return 结果
     */
    @Override
    public boolean checkCategoryCodeUnique(PetCategory petCategory)
    {
        Long categoryId = StringUtils.isNull(petCategory.getCategoryId()) ? -1L : petCategory.getCategoryId();
        PetCategory info = petCategoryMapper.checkCategoryCodeUnique(petCategory.getCategoryCode());
        if (StringUtils.isNotNull(info) && info.getCategoryId().longValue() != categoryId.longValue())
        {
            return false;
        }
        return true;
    }

    /**
     * 构建树形结构的分类列表
     * 
     * @param categories 分类集合
     * @return 树形结构集合
     */
    @Override
    public List<PetCategory> buildCategoryTree(List<PetCategory> categories)
    {
        List<PetCategory> rootCategories = new ArrayList<>();
        Map<Long, PetCategory> categoryMap = new HashMap<>();
        
        // 先把所有分类放入Map
        for (PetCategory category : categories) {
            categoryMap.put(category.getCategoryId(), category);
            category.setChildren(new ArrayList<>());
        }
        
        // 构建树形结构
        for (PetCategory category : categories) {
            if (category.getParentId() != null && category.getParentId() != 0) {
                // 子节点
                PetCategory parent = categoryMap.get(category.getParentId());
                if (parent != null) {
                    parent.getChildren().add(category);
                }
            } else {
                // 根节点
                rootCategories.add(category);
            }
        }
        
        return rootCategories;
    }

    /**
     * 查询顶级分类列表
     * 
     * @return 顶级分类集合
     */
    @Override
    public List<PetCategory> selectTopLevelCategories()
    {
        return petCategoryMapper.selectTopLevelCategories();
    }

    /**
     * 根据父级ID查询子分类
     * 
     * @param parentId 父级ID
     * @return 子分类集合
     */
    @Override
    public List<PetCategory> selectCategoriesByParentId(Long parentId)
    {
        return petCategoryMapper.selectCategoriesByParentId(parentId);
    }

    /**
     * 查询所有有效的子分类
     * 
     * @return 子分类集合
     */
    @Override
    public List<PetCategory> selectActiveSubCategories()
    {
        return petCategoryMapper.selectActiveSubCategories();
    }

    /**
     * 获取分类及其对应的子分类名称映射
     * 
     * @return 分类名称映射
     */
    @Override
    public Map<String, List<String>> listCategoriesWithNames()
    {
        Map<String, List<String>> categoryNamesMap = new HashMap<>();
        
        // 获取所有顶级分类
        List<PetCategory> topCategories = selectTopLevelCategories();
        
        for (PetCategory topCategory : topCategories) {
            List<String> subCategoryNames = new ArrayList<>();
            
            // 获取该顶级分类下的所有子分类
            List<PetCategory> subCategories = selectCategoriesByParentId(topCategory.getCategoryId());
            for (PetCategory subCategory : subCategories) {
                subCategoryNames.add(subCategory.getCategoryName());
            }
            
            categoryNamesMap.put(topCategory.getCategoryName(), subCategoryNames);
        }
        
        return categoryNamesMap;
    }
}